package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.SearchService;
import com.heima.search.service.UserSearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {


    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    UserSearchService userSearchService;
    /**
     * 根据关键词搜索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws Exception {
        //检查参数
        if (dto==null||dto.getSearchWords()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询索引库
        SearchRequest request=new SearchRequest("app_info_article");

        //创建条件构建器
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
        //创建布尔查询对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //根据关键词查询
       boolQueryBuilder.must(QueryBuilders.wildcardQuery("title",dto.getSearchWords()));
        //根据时间查询
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").gte(dto.getMinBehotTime()));
       searchSourceBuilder.query(boolQueryBuilder);

        //根据排序查询
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        //分页查询
        searchSourceBuilder.from(dto.getPageNum());
        searchSourceBuilder.size(dto.getPageSize());
        request.source(searchSourceBuilder);

        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
       //获取文章集合
        SearchHit[] hits = response.getHits().getHits();

        //创建集合保存文章信息
        ArrayList<Map> list=new ArrayList<>();
        //遍历获取信息
        for (SearchHit hit : hits) {
            String source = hit.getSourceAsString();
            Map map = JSON.parseObject(source, Map.class);
            list.add(map);
        }

        //保存用户查询的关键词到mysql  ap_user_search
        //创建线程池，实现多线程异步调用
        //只保存第一次搜索记录，因为后面搜索的都是同一个词,减少线程的创建
        if (dto.getPageNum()==0){
            userSearchService.saveSearch(dto);
        }

        return ResponseResult.okResult(list);
    }
}
